import axios from 'axios';
import JSZip from 'jszip';
import { Sitdown } from 'sitdown'
import { TmpFile } from './converter';
import localforage from 'localforage';
import { saveAs } from 'file-saver'
let sitdown = new Sitdown({
  keepFilter: ['style'],
  codeBlockStyle: 'fenced',
  bulletListMarker: '-',
  hr: '---',
});
enum BlockType {
  page = 'page',//
  text = 'text',       //
  h1 = 'heading1',         //
  h2 = 'heading2',         //
  h3 = 'heading3',         //
  h4 = 'heading4',         //
  h5 = 'heading5',             //
  h6 = 'heading6',             //
  h7 = 'heading7',             //
  h8 = 'heading8',             //
  h9 = 'heading9',             //
  bullet = 'bullet',    //
  orderList = 'orderList',      //
  code = 'code',           //
  ref = 15,       //
  equation,
  todo = 'todo',           //
  bitable = 19,
  callout,
  chat_card,
  diagram,
  divider,           //
  file = 23,
  grid,            //
  grid_column,       //
  iframe,
  image = 'image',          //
  widget = 29,
  mindnote,
  sheet,
  table,
  tabel_cell,
  view,
  // ----
  quote = 34,     //
  unsupport = 999
}

let renderBullet: string[] = []
async function converBlock(md: string, block: any, zip: JSZip, blockId: string, blockMap: any, parent_prefix?: string) {
  const { data: blockData, id } = block
  const { type, text, image, done } = blockData
  console.log("🚀 ~ converBlock ~ type:", type)
  switch (type) {
    case BlockType.page:
      md += `# ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.text:
      md += `${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h1:
      md += `# ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h2:
      md += `## ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h3:
      md += `### ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h4:
      md += `#### ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h5:
      md += `##### ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h6:
      md += `###### ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h7:
      md += `####### ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h8:
      md += `######## ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h9:
      md += `######### ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.todo:
      if (done) {
        md += `- [x] ${text.initialAttributedTexts.text[0]}\n`
      } else {
        md += `- [ ] ${text.initialAttributedTexts.text[0]}\n`
      }
      break
    case BlockType.bullet:
      md += `${parent_prefix ? parent_prefix : ''}* ${text.initialAttributedTexts.text[0]}\n`
      const { children } = blockData
      if (children) {
        for (let i = 0; i < children.length; i++) {
          if (renderBullet.includes(children[i])) {
            continue
          }
          await converBlock(md, blockMap[children[i]], zip, children[i], blockMap, "  ")
          renderBullet.push(id)
        }
      }
      break
    case BlockType.orderList:
      break
    case BlockType.code:
      break
    case BlockType.image:
      const token = image.token
      const name = image.name
      const mimeType = image.mimeType
      const fileName = await downloadAsset(token, blockId, zip, name)
      md += `![](assets/${fileName})\n`
      console.log(blockData, 'image', id)
      break
  }
  return md
}
// https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/v2/cover/WP2SbluZxoLAQBxiW3LcWtGtnNe/?fallback_source=1&height=1280&mount_node_token=KgmtdKXxooOCeuxHeY9c4qtMnhe&mount_point=docx_image&policy=equal&width=1280
// https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/v2/cover/SpV0bXNOwoOo6TxNtivcvbCBn5g/?fallback_source=1&height=1280&mount_node_token=Xc6vdIqJDoeTmGxpm9ScUfyXnfd&mount_point=docx_image&policy=equal&width=1280
// https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/v2/cover/GRceb68A4oHFrCxCKp8cyztUn8f/?fallback_source=1&height=1280&mount_node_token=BND1d4MdkodcKpxr2q3ceG0InZe&mount_point=docx_image&policy=equal&width=1280
// https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/preview/MY6ubl5qBotoG2x1bfWc3ZnanGe/?preview_type=16
// blob:https://ry5hwpuf7b.feishu.cn/d8281a51-1116-4ee2-af04-1fb75c5a364d

const tmp = localforage.createInstance({
  name: 'file_cache'
})
async function downloadAsset(token: string, nodeToken: string, zip: JSZip, name?: string) {
  let c = await tmp.getItem<TmpFile>(token)
  let ext = { value: "" }
  function get_ext(mim: string) {
      const mtype = mim.split("/")
      if (mtype.length === 2) {
          ext.value = "." + mtype[1]
      } else {
          console.log(mtype)
      }
  }
  if (c) {
      let mime = c.mime
      get_ext(mime)
      zip.folder("assets")?.file(name ? (token + "_" + name) : (token + ext.value), c.data)
  } else {
      // const url = `https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/v2/cover/${token}/?fallback_source=1&height=1280&mount_node_token=${nodeToken}&mount_point=docx_image&policy=equal&width=1280`
      const url = `https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/preview/${token}/?preview_type=16`
      console.log('🚀 ~ downloadAsset ~ url:', url)
      let r = await axios.get(url,
          {
              responseType: 'arraybuffer',
              headers: {
                "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
                "Referer": "https://vliajwma3m.feishu.cn",
                "origin": "https://vliajwma3m.feishu.cn",
                Origin:"https://vliajwma3m.feishu.cn",
                "Sec-Ch-Ua": `"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"`,
                "Sec-Ch-Ua-Mobile":
                "?0",
                "Sec-Ch-Ua-Platform":
                "macOS"
              }
          })
      let mime = r.headers['content-type']
      get_ext(mime)
      const data = new Uint8Array(r.data)
      zip.folder("assets")?.file(name ? (token + "_" + name) : (token + ext.value), data)
      await tmp.setItem(token, {
          mime: mime,
          data: data
      })
  }
  return name ? (token + "_" + name) : (token + ext.value)
}

export const convert = async (blockMap: any, queues: string[], title='') => {
console.log('🚀 ~ convert ~ blockMap:', blockMap, queues)

  let markdownContent = ''
  renderBullet = []
  const jsZip = new JSZip()

  for (let i = 0; i < queues.length; i++) {
    const block = blockMap[queues[i]]
    console.log('🚀 ~ convert ~ block:', block)
    markdownContent = await converBlock(markdownContent, block, jsZip, queues[i], blockMap)
  }

  jsZip.file(`${title}.md`, markdownContent)

  jsZip.generateAsync({ type: "blob" }).then(function (content) {
    saveAs(content, "example.zip");
  })
  console.log(markdownContent, '==============')
}